package com.feicheng.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feicheng.common.constant.Constant;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.message.LoginMessage;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.persistence.entity.Account;
import com.feicheng.persistence.entity.Client;
import com.feicheng.persistence.entity.Store;
import com.feicheng.persistence.entity.StoreClient;
import com.feicheng.persistence.entity.StoreWx;
import com.feicheng.persistence.entity.WxServer;
import com.feicheng.persistence.service.IAccountService;
import com.feicheng.persistence.service.IClientService;
import com.feicheng.persistence.service.IStoreClientService;
import com.feicheng.persistence.service.IStoreService;
import com.feicheng.persistence.service.IStoreWxService;
import com.feicheng.persistence.service.IWxServerService;
import com.feicheng.service.BaseService;
import com.feicheng.service.IFLoginService;
import com.feicheng.wxapi.app.WxApi;

/**
 * @see com.feicheng.service.IFLoginService
 */
@Service
public class FClientWxAppLoginServiceImpl extends BaseService implements IFLoginService {

    @Autowired
    LoginMessage loginMessage;

    @Autowired
    WxApi wxApi;
    
    @Autowired
    IStoreService storeService;

    @Autowired
    IClientService clientService;

    @Autowired
    IAccountService accountService;

    @Autowired
    IStoreClientService storeClientService;

    @Autowired
    IStoreWxService storeWxService;

    @Autowired
    IWxServerService wxServerService;

    /**
     * 登录
     *
     * @param loginParams 登录参数
     * @return
     */
    @Transactional
    @Override
    public ResultInfo login(String loginParams) {
    	JSONObject result = new JSONObject();
    	JSONObject param = JSONObject.parseObject(loginParams);
    	String code = param.getString(Constant.WX.PARAM.CODE);
    	String appId = param.getString(Constant.WX.PARAM.APPID);
    	String phoneCode = param.getString("PHONE_CODE");
    	
    	/* 取得门店信息 */
    	QueryWrapper<WxServer> wxServerQueryWrapper = new QueryWrapper<WxServer>();
        wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.APP_ID, appId);
        wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.WX_TYPE, Constant.VAL.WX_TYPE.Y);
        wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.STATU, true);
        wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.D_FLG, false);
        List<WxServer> wxServers = wxServerService.list(wxServerQueryWrapper);
        if (1 != wxServers.size()) {
            throw new SystemException("取得门店小程序信息失败！");
        }

        WxServer wxServer = wxServers.remove(0);

        QueryWrapper<StoreWx> storeWxQueryWrapper = new QueryWrapper<StoreWx>();
        storeWxQueryWrapper.eq(Constant.ENTITY.STORE_WX.W_ID, wxServer.getWId());
        List<StoreWx> storeWxes = storeWxService.list(storeWxQueryWrapper);

        if (1 != storeWxes.size()) {
            throw new SystemException("取得门店信息失败");
        }

        Store store = storeService.getById(storeWxes.remove(0).getStoreId());
        
        /* 取得openId */
        String openId = wxApi.getOpenId(
        		code, 
        		wxServer.getAppId(), 
        		wxServer.getAccessKey());
        
        /* 取得电话号 */
        String phone = wxApi.getPhoneNumber(
        		store.getStoreId(), 
        		openId, 
        		wxServer.getAppId(), 
        		wxServer.getAccessKey(), 
        		phoneCode);
        
        QueryWrapper<StoreClient> storeClientQueryWrapper = new QueryWrapper<StoreClient>();
	    storeClientQueryWrapper.eq(Constant.ENTITY.STORE_CLIENT.STORE_ID, store.getStoreId());
	    storeClientQueryWrapper.eq(Constant.ENTITY.STORE_CLIENT.OPEN_ID, openId);
	    storeClientQueryWrapper.eq(Constant.ENTITY.STORE_CLIENT.WX_TYPE, Constant.VAL.WX_TYPE.Y);
	    List<StoreClient> storeClientList = storeClientService.list(storeClientQueryWrapper);
	    
	    if (0 == storeClientList.size()) {
	    	
	    	QueryWrapper<Client> clientQueryWrapper = new QueryWrapper<Client>();
	    	clientQueryWrapper.eq("phone", phone);
	    	clientQueryWrapper.eq("d_flg", false);
	    	List<Client> clients = clientService.list(clientQueryWrapper);
	    	if (0 == clients.size()) {
	            Client client = new Client();
	            client.setClientName("未设定");
	            client.setHeadImgUrl("https://bpic.588ku.com/element_origin_min_pic/23/02/19/68be03bac2bb3c3bfbaaf59a951bfbe7.jpg");
	            client.setPhone(phone);
	            clientService.save(client);
	
	            StoreClient sc = new StoreClient();
	            sc.setClientId(client.getClientId());
	            sc.setOpenId(openId);
	            sc.setStoreId(store.getStoreId());
	            sc.setWxType(Constant.VAL.WX_TYPE.Y);
	            storeClientService.save(sc);
	
	            Account account = new Account();
	            account.setClientId(client.getClientId());
	            account.setDepositAmount(0);
	            account.setTimeLongs(0);
	            accountService.save(account);
	
	            result.put(Constant.ENTITY.CLIENT.TABLE, client);
	            result.put(Constant.ENTITY.STORE_CLIENT.TABLE, sc);
	            result.put(Constant.ENTITY.ACCOUNT.TABLE, account);
            } else if (1 == clients.size()) {
            	
            	Client client = clients.remove(0);
            	StoreClient sc = new StoreClient();
 	            sc.setClientId(client.getClientId());
 	            sc.setOpenId(openId);
 	            sc.setStoreId(store.getStoreId());
 	            sc.setWxType(Constant.VAL.WX_TYPE.Y);
 	            storeClientService.save(sc);
 	            
 	            result.put(Constant.ENTITY.CLIENT.TABLE, client);
 	            result.put(Constant.ENTITY.STORE_CLIENT.TABLE, sc);
	           
 	            QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<Account>();
 	            accountQueryWrapper.eq(Constant.ENTITY.ACCOUNT.CLIENT_ID, client.getClientId());
 	            List<Account> accountList = accountService.list(accountQueryWrapper);

 	            if (1 != accountList.size()) {
 	            	throw new SystemException(loginMessage.getE05());
 	            }

 	            result.put(Constant.ENTITY.ACCOUNT.TABLE, accountList.remove(0));
            	
            } else {
            	throw new SystemException("当前电话号非法");
            }
	    	
	    	
	    } else if (1 == storeClientList.size()) {
            StoreClient sc = storeClientList.remove(0);
            Client client = clientService.getById(sc.getClientId());

            QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<Account>();
            accountQueryWrapper.eq(Constant.ENTITY.ACCOUNT.CLIENT_ID, client.getClientId());
            List<Account> accountList = accountService.list(accountQueryWrapper);

            if (1 != accountList.size()) {
                throw new SystemException(loginMessage.getE05());
            }

            result.put(Constant.ENTITY.CLIENT.TABLE, client);
            result.put(Constant.ENTITY.STORE_CLIENT.TABLE, sc);
            result.put(Constant.ENTITY.ACCOUNT.TABLE, accountList.remove(0));
        }
	    
	    result.put(Constant.ENTITY.STORE.TABLE, store);
	    return ResultInfo.success(result);

//        JSONObject result = new JSONObject();
//        /* 取得登录所需的参数 jscode ，转换出现问题时抛出异常，登录逻辑停止。*/
//        JSONObject param = null;
//        try {
//            param = JSONObject.parseObject(loginParams);
//        } catch (JSONException exception) {
//            throw new SystemException(loginMessage.getE01());
//        }
//
//        String code = param.getString(Constant.WX.PARAM.CODE);
//        Integer storeId = param.getInteger(Constant.ENTITY.STORE.STORE_ID);
//
//        Store store = storeService.getById(storeId);
//
//        QueryWrapper<StoreWx> storeWxQueryWrapper = new QueryWrapper<StoreWx>();
//        storeWxQueryWrapper.eq(Constant.ENTITY.STORE_WX.STORE_ID, storeId);
//        List<StoreWx> storeWxList = storeWxService.list(storeWxQueryWrapper);
//
//        if (0 == storeWxList.size()) {
//            throw new SystemException(loginMessage.getE08());
//        }
//
//        JSONArray wxIds = new JSONArray();
//        for (StoreWx sw : storeWxList) {
//            wxIds.add(sw.getWId());
//        }
//
//        QueryWrapper<WxServer> wxServerQueryWrapper = new QueryWrapper<WxServer>();
//        wxServerQueryWrapper.in(Constant.ENTITY.WX_SERVER.W_ID, wxIds);
//        wxServerQueryWrapper.eq(Constant.ENTITY.WX_SERVER.WX_TYPE, Constant.VAL.WX_TYPE.Y);
//        List<WxServer> wxServerList = wxServerService.list(wxServerQueryWrapper);
//
//        if (0 == wxServerList.size()) {
//            throw new SystemException(loginMessage.getE08());
//        }
//
//        WxServer wxServer = wxServerList.remove(0);
//        result.put(Constant.ENTITY.WX_SERVER.TABLE, wxServer);
//        String openId = wxApi.getOpenId(code, wxServer.getAppId(), wxServer.getAccessKey());
////        String openId = "o5_mI1DNxJwcUkUR0ylUOS9Al5WI";
//        QueryWrapper<StoreClient> storeClientQueryWrapper = new QueryWrapper<StoreClient>();
//        storeClientQueryWrapper.eq(Constant.ENTITY.STORE_CLIENT.STORE_ID, storeId);
//        storeClientQueryWrapper.eq(Constant.ENTITY.STORE_CLIENT.OPEN_ID, openId);
//        storeClientQueryWrapper.eq(Constant.ENTITY.STORE_CLIENT.WX_TYPE, Constant.VAL.WX_TYPE.Y);
//        
//        synchronized (openId.intern()) {
//        	List<StoreClient> storeClientList = storeClientService.list(storeClientQueryWrapper);
//
//	        if (0 == storeClientList.size()) {
//
//	            Client client = new Client();
//	            client.setClientName("未设定");
//	            client.setHeadImgUrl("https://bpic.588ku.com/element_origin_min_pic/23/02/19/68be03bac2bb3c3bfbaaf59a951bfbe7.jpg");
//	            clientService.save(client);
//	
//	            StoreClient sc = new StoreClient();
//	            sc.setClientId(client.getClientId());
//	            sc.setOpenId(openId);
//	            sc.setStoreId(storeId);
//	            sc.setWxType(Constant.VAL.WX_TYPE.Y);
//	            storeClientService.save(sc);
//	
//	            Account account = new Account();
//	            account.setClientId(client.getClientId());
//	            account.setDepositAmount(0);
//	            account.setTimeLongs(0);
//	            accountService.save(account);
//	
//	            result.put(Constant.ENTITY.CLIENT.TABLE, client);
//	            result.put(Constant.ENTITY.STORE_CLIENT.TABLE, sc);
//	            result.put(Constant.ENTITY.ACCOUNT.TABLE, account);
//	
//	        } else if (1 == storeClientList.size()) {
//	            StoreClient sc = storeClientList.remove(0);
//	            Client client = clientService.getById(sc.getClientId());
//	
//	            QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<Account>();
//	            accountQueryWrapper.eq(Constant.ENTITY.ACCOUNT.CLIENT_ID, client.getClientId());
//	            List<Account> accountList = accountService.list(accountQueryWrapper);
//	
//	            if (1 != accountList.size()) {
//	                throw new SystemException(loginMessage.getE05());
//	            }
//	
//	            result.put(Constant.ENTITY.CLIENT.TABLE, client);
//	            result.put(Constant.ENTITY.STORE_CLIENT.TABLE, sc);
//	            result.put(Constant.ENTITY.ACCOUNT.TABLE, accountList.remove(0));
//	        }
//        
//        }
//        result.put(Constant.ENTITY.STORE.TABLE, store);
//        return ResultInfo.success(result);
    }
}
